<template>
  <div class="baseinfo">
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="项目编号" prop="projectNo" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
            {{form.projectNo}}
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="projectName"
            label="项目名称"
            prop="projectName"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.projectName"
              @blur="
                () => {
                  $refs.projectName.onFieldBlur()
                }
              "
              placeholder="请输入有效的项目名称" 
               :disabled="form.status>1" 
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="mainDeptName"
            label="主导经营体"
            prop="mainDeptName"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.mainDeptName"
              @blur="
                () => {
                  $refs.mainDeptName.onFieldBlur()
                }
              "
              placeholder="请填写正确的组织架构名称，系统自动校验"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
      <a-col :span="8">
        <a-form-model-item
          label="项目分类"
          prop="projectTypeSubCategory"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 15 }"
        >
          <a-select
            v-model="form.projectTypeSubCategory"
            placeholder="请选择项目分类"
            :options="projectCategoryOptions" 
             :disabled="form.status>1"
            @change="projectTypeChange"
          >
            <a-icon slot="suffixIcon" type="plus" />
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item
          ref="hatchProjectNo"
          label="孵化项目编号"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 15 }"
        >
          <a-input v-model="form.hatchProjectNo" placeholder="点击选择孵化项目" @click="hatch.visible = true"  :disabled="form.status>1" />
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item
          ref="hatchProjectName"
          label="孵化项目名称"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 15 }"
        >
          <a-input v-model="form.hatchProjectName" placeholder="点击选择孵化项目" @click="hatch.visible = true"  :disabled="form.status>1" />
        </a-form-model-item>
      </a-col>
    </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            label="投资类型"
            prop="investType"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              v-model="form.investType"
              placeholder="请选择投资类型"
              :options="investTypeOptions"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            label="所属行业"
            prop="investIndustry"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input v-model="form.investIndustry" placeholder="请输入所属行业"   :disabled="form.status>1" />
          </a-form-model-item>
        </a-col>
      </a-row>
      
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="projectContent"
            label="项目简介"
            prop="projectContent"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.projectContent"
              @blur="
                () => {
                  $refs.projectContent.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <!--
        <a-row :gutter="24" v-if="form.investType == '1'">
        <a-col :span="24">
          <a-form-model-item
            ref="mainIP"
            label="核心知识产权"
            prop="mainIP"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.mainIP"
              @blur="
                () => {
                  $refs.projectContent.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
              placeholder="请描述会影响本项目价值的最核心知识产权"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      -->
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="targetEnterprise"
            label="标的企业"
            prop="targetEnterprise"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.targetEnterprise"
              @blur="
                () => {
                  $refs.targetEnterprise.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="economyTarget"
            label="投资价值"
            prop="economyTarget"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.economyTarget"
              @blur="
                () => {
                  $refs.economyTarget.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
              placeholder="行业方面主要是看行业机会，如政策红利、发展空间、消费趋势、竞争格局；企业方面主要是看企业的核心竞争力，比如资源优势、盈利水平、成长空间等（比如知名商标、领先的技术专利等知识产权、稀缺性资源或者采购原料或者经营牌照）（300字以内）"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="technologyTarget"
            label="投资风险"
            prop="technologyTarget"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.technologyTarget"
              @blur="
                () => {
                  $refs.technologyTarget.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
              placeholder="重点关注产权风险（如土地厂房、知识产权等是否存在争议或者不稳定）、财务风险（债务、担保）、政策合规风险（如环保、土地、行业限制等）（300字以内）"
            />
          </a-form-model-item>
        </a-col>
      </a-row>

      <h3><b>项目相关方</b></h3>
      <div style="display: flex; margin-top: 10px; margin-bottom: 10px">
        <a-button type="primary" @click="kpiAdd()">新增</a-button>
        <a-button style="margin-right: 15px" class="default" @click="kpiDel()">删除</a-button>
      </div>
      <a-table
        :row-selection="rowSelection"
        :columns="kpi.columns"
        :data-source="kpi.data"
        bordered
        :key="kpi.freshKey"
      >
        <template slot="companyName" slot-scope="text, record">
          <a-textarea v-model="record.companyName" placeholder="250字以内" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="250"/>
        </template>
        <template slot="role" slot-scope="text, record">
          <a-textarea v-model="record.role" placeholder="50字以内" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="50"/>
        </template>
      </a-table>

      <five-to-five ref="fiveForm" :projectBuildId="projectBuildId" :change-id="changeId" @addField="addFiveDataToForm"/>
    </a-form-model>

    <pagination-select
      :title="hatch.title"
      :searchPlaceholder="hatch.searchPlaceholder"
      :visible="hatch.visible"
      :url="hatch.url"
      :columns="hatch.columns"
      @hatchHandleOk="hatchHandleOk"
    />

    <user-select ref="companySelect" @setResult="setResult" :outUrl="url.queryCompanyUrl"  title="选择公司(可以多选)"
        :outColumns="tabColumnsOut" :outKey="projectBuildId" :originTargetKeys="originTargetKeys"/>

  </div>
</template>
<script>
import $ from 'jquery'
import { getAction, getActionAsync, postAction, postActionAsync } from '@/api/manage'
import { getParamValFromUrl, strNotNull } from '@/utils/common.js'
import { Modal } from 'ant-design-vue'
import Vue from 'vue'
export default {
  components: {
    PaginationSelect: () => import('@/components/tools/PaginationSelect'),
    UserSelect: () => import('@/components/tools/UserSelect'),
    FiveToFive: () => import('@/components/tools/projectBuildStup/baseInfo/FiveToFive')
  },
  props: {
    projectBuildId: {
      Type: String,
      default: '',
    },
    changeId: {
      Type: String,
      default: '',
    }
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      other: '',
      kpi: {
        columns: [
          {
            title: '公司名称',
            dataIndex: 'companyName',
            width: '70%',
            scopedSlots: { customRender: 'companyName' },
          },
          {
            title: '角色',
            dataIndex: 'role',
            width: '30%',
            scopedSlots: { customRender: 'role' },
          }
        ],
        data: [],
        selRowIds: [],
        freshKey: 0,
      },
      form: {
        id:'',
        projectClass: '50',
        projectNo: '',
        projectName: '',
        mainDeptName: '',
        projectTypeSubCategory: '',
        hatchProjectId: '',
        hatchProjectNo: '',
        hatchProjectName: '',
        projectContent: '',
        technologyTarget: '',
        economyTarget: '',
        investType:'',
        investIndustry:'',
        targetEnterprise:'',
        mainIP:'',
        status: 0 ,
        involveCompany:'',
        involveCompanyCode: ''
      },
      rules: {
        projectName: [
          { required: true, message: '请输入有效的项目名', trigger: 'blur' },
          { min: 1, max: 50, message: '项目名不超过50个字符', trigger: 'blur' },
        ],
        projectContent: [
          { required: true, message: '请输入项目概述', trigger: 'blur' },
          { min: 1, max: 2000, message: '项目概述不超过2000个字符', trigger: 'blur' },
        ],
        technologyTarget: [
          { required: true, message: '请输入项目技术目标', trigger: 'blur' },
          { min: 1, max: 300, message: '项目技术目标不超过300个字符', trigger: 'blur' },
        ],
        economyTarget: [
          { required: true, message: '请输入项目经济目标', trigger: 'blur' },
          { min: 1, max: 300, message: '项目经济目标不超过300个字符', trigger: 'blur' },
        ],
        mainDeptName: [
          { required: true, message: '请输入主导经营体', trigger: 'blur' },
          { min: 1, max: 300, message: '主导经营体不超过300个字符', trigger: 'blur' },
        ],
        // mainIP: [
        //   { required: true, message: '请输入核心知识产权', trigger: 'blur' },
        //   { min: 1, max: 300, message: '核心知识产权不超过300个字符', trigger: 'blur' },
        // ],
        projectTypeSubCategory: [{ required: true, message: '请选择项目分类', trigger: 'change' }],
        investType: [{ required: true, message: '请选择投资类型', trigger: 'change' }],
      },

      projectCategoryOptions: [],
      investTypeOptions: [],
      investIndustryOptions: [],
      url: {
        codeInfoList: '/manage/codeInfo/list',
        getProjectByNo: '/projectBuild/getProjectByNo',
        save: '/projectBuild/add',
        queryVOById: '/projectBuild/queryVOById',
        getReportByHatch:'/projectBuild/getReportByHatch',
        queryCompanyUrl: '/rad/orgCompany/queryCompany'
      },
      hatch: {
        visible: false,
        title: '请选择孵化项目',
        searchPlaceholder: '输入代码或名称查询',
        url: '/hatchProject/listBySelect?projectClass=50',
        columns: [
          {
            title: '孵化项目编号',
            dataIndex: 'hatchProjectNo',
            align: 'center',
          },
          {
            title: '孵化项目名称',
            dataIndex: 'hatchProjectName',
            align: 'center',
          },
        ],
      },
      loadFinish: false,
      tabColumnsOut:[
        {
          dataIndex: 'code',
          title: '编号',
        },
        {
          dataIndex: 'name',
          title: '公司名称',
        },
      ],
      originTargetKeys: []
    }
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.kpi.selRowIds = selectedRowKeys
        },
      }
    },
  },
  methods: {
    addFiveDataToForm(val,valRef) {
      this.$set(this.form, valRef, val)
    },
    async doSubmit() {
      if(!this.loadFinish){
        layer.message.warning('请等待页面加载完毕')
        return {}  
      }
      var validR=false;
      try{
        validR = await this.$refs.ruleForm.validate();
        validR = await this.$refs.fiveForm.checkFiveWriteStatus()
      }catch(e){
        validR = false;
      }
      console.log('validR',validR);
      this.form.validResult = validR;
      let res=await this.doSave()
      return {valid:validR,id:res};
    },
    async doSave() {
      let flag=null;
      this.form.investVOList = this.kpi.data
 
      var formData = JSON.parse(JSON.stringify(this.form));
      formData.changeId = this.changeId;
      var vm = this
      await postActionAsync(this.url.save, formData)
        .then((res) => {
          if (res.code == 200) {
            vm.form.id = res.result.id;
            vm.form.projectNo = res.result.projectNo;
            this.$message.success('保存成功')
            return flag=res.result.id;
          } else {
            this.$message.warning('保存数据出错:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('保存数据出错:' + res.message)
        })
        return flag;
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    kpiAdd() {
      this.kpi.data.push({
        key: this.kpi.data.length + 1 + new Date().getTime(),
        strId: '',
        companyName: '',
        role: '',
      })
    },
    kpiDel() {
      debugger
      if (this.kpi.selRowIds.length == 0) {
        this.$message.warning('请选择要删除的项目相关方记录')
        return
      }
      var vm=this;
      Modal.confirm({
        title: '警告',
        content: '真的要删除吗?',
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          console.log('OK')
          // 在这里调用删除接口
          for (var i = 0; i < vm.kpi.selRowIds.length; i++) {
            for (var j = vm.kpi.data.length - 1; j >= 0; j--) {
              if (vm.kpi.data[j].key == vm.kpi.selRowIds[i]) {
                vm.kpi.data.splice(j, 1)
                break
              }
            }
          }
          vm.kpi.selRowIds = []
          vm.kpi.freshKey++
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    setResult(result) {
      if (result == null) {
        this.$message.warning('选择不能为空可以多选');
        return ;
      }
      const that = this
      if (result != null) {
        const companySet = new Set()
        const originTargetKeysSet = new Set()
        result.forEach((item) => {
          originTargetKeysSet.add(item.code)
          companySet.add(item.name)
        })
        this.originTargetKeys = Array.from(originTargetKeysSet)
        this.$set(this.form,'involveCompany', Array.from(companySet).join())
        this.$set(this.form,'involveCompanyCode', this.originTargetKeys.join())
      }
    },
    findCompany() {
      this.$refs.companySelect.doSelect()
    },
    //初始化项目子类
    initProjectCategoryOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0, parentid: vm.form.projectClass })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.projectCategoryOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询项目子类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目子类失败:' + res.message)
        })
    },
    //初始化投资类型
    initInvestTypeOptions(value) {
      var vm = this
      vm.investTypeOptions = [];
      vm.investTypeOptions.push({value:"",label:"请选择投资类型"});
      getAction(this.url.codeInfoList, { type: '投资类型'+value, isdel: 0, parentid: null })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.investTypeOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询投资类型失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目子类失败:' + res.message)
        })
    },
    //孵化项目选中
    hatchHandleOk(record) {
      if (record != null && record.length > 0) {
        this.form.hatchProjectId = record[0].id
        this.form.hatchProjectNo = record[0].hatchProjectNo
        this.form.hatchProjectName = record[0].hatchProjectName
        getAction(this.url.getReportByHatch,{hatchId:record[0].id}).then(res =>{
          if(res.code==200){
            let result = res.result;
            if(result != null){
              this.form.projectTypeSubCategory = result.projectType;
              this.form.projectContent = result.projectContent;
              this.form.technologyTarget = result.technologyTarget;
              this.form.economyTarget = result.economyTarget;
              this.initInvestTypeOptions(result.projectType);
              this.form.investType = result.investType;
              this.form.mainIP = result.mainIP;
            }
          }
        })
      }
      this.hatch.visible = false
    },
    projectTypeChange(value){
      this.form.investType = ''
      this.initInvestTypeOptions(value);
    },
    //如果有id，则加载已填写信息
    initData() {
      if (this.projectBuildId != null && this.projectBuildId != '') {
        var vm = this
        getAction(this.url.queryVOById, { id: this.projectBuildId,changeId: this.changeId })
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form = result
                if (this.form.isHighTechProject) {
                  this.form.isHighTechProjectText = '高企项目'
                } else {
                  this.form.isHighTechProjectText = '非高企项目'
                }
                if(this.form.projectTypeSubCategory != null && this.form.projectTypeSubCategory != ''){
                  this.initInvestTypeOptions(this.form.projectTypeSubCategory);
                }
                if (this.form.involveCompanyCode != null && this.form.involveCompanyCode != '') {
                  this.originTargetKeys = this.form.involveCompanyCode.split(",");
                }
                if (result.investVOList != null) {
                  this.kpi.data = result.investVOList
                  this.kpi.data.forEach((item) => {
                    item.key = item.strId
                  })
                }
                
                this.loadFinish=true
              } else {
                vm.$message.warning('初始化项目信息为空')
              }
            } else {
              this.$message.warning('初始化项目信息失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('初始化项目信息失败:' + res.message)
          })
      }else{
        this.loadFinish=true
      }
    },
  },
  mounted() {
    this.initProjectCategoryOptions()
    this.initData()
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-btn-primary {
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #4095e4;
  margin-right: 10px;
}
/deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
  .btn {
    display: flex;
    justify-content: center;
  }
}
</style>